﻿using FileTransferDesktop.Views.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Wpf.Ui;
using Wpf.Ui.Appearance;

namespace FileTransferDesktop.Services;

/// <summary>
/// Managed host of the application.
/// </summary>
public class ApplicationHostService : IHostedService
{
    private readonly IServiceProvider _serviceProvider;

    private INavigationWindow? _navigationWindow;

    public ApplicationHostService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// Triggered when the application host is ready to start the service.
    /// </summary>
    /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await HandleActivationAsync();
        // 在启动时恢复主题设置
        await RestoreThemeSettings();
    }

    /// <summary>
    /// Triggered when the application host is performing a graceful shutdown.
    /// </summary>
    /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        await Task.CompletedTask;
    }

    /// <summary>
    /// Creates main window during activation.
    /// </summary>
    private async Task HandleActivationAsync()
    {
        if (!Application.Current.Windows.OfType<MainWindow>().Any())
        {
            _navigationWindow = (
                _serviceProvider.GetService(typeof(INavigationWindow)) as INavigationWindow
            )!;
            _navigationWindow!.ShowWindow();

            _navigationWindow.Navigate(typeof(Views.Pages.DashboardPage));
        }

        await Task.CompletedTask;
    }

    /// <summary>
    /// 恢复保存的主题设置
    /// </summary>
    private async Task RestoreThemeSettings()
    {
        try
        {
            var appSettingsService = _serviceProvider.GetService<IAppSettingsService>();
            if (appSettingsService != null)
            {
                var settings = await appSettingsService.GetSettingsAsync();

                switch (settings.Theme)
                {
                    case "Light":
                        ApplicationThemeManager.Apply(ApplicationTheme.Light);
                        break;
                    case "Dark":
                        ApplicationThemeManager.Apply(ApplicationTheme.Dark);
                        break;
                    case "System":
                    default:
                        ApplicationThemeManager.Apply(ApplicationTheme.Unknown);
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            // 如果恢复主题设置失败，使用默认主题
            System.Diagnostics.Debug.WriteLine($"Failed to restore theme settings: {ex.Message}");
            ApplicationThemeManager.Apply(ApplicationTheme.Unknown);
        }
    }
}
